import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/main/page/address_page.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/event/click_user_info_event.dart';
import 'package:flutter_rider/event/click_address_event.dart';
import 'package:flutter_rider/utils/alib.dart';

class UserInfoPage extends StatefulWidget {
  String username;
  String phone;
  String address;
  String carPlate;
  String lat;
  String lng;
  String stationName;
  String stationId;
  String aliasName;
  int aliasId;
  int type;
  UserInfoPage(this.username,
      this.phone,
      this.address,
      this.carPlate,
      this.lat,
      this.lng,
      this.stationName,
      this.stationId,
      this.aliasName,
      this.aliasId,
      this.type,
      {Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return UserInfoPageState();
  }
}

class UserInfoPageState extends State<UserInfoPage> {
  late StreamSubscription _eventFn;
  final _nameTextController = TextEditingController();
  final _phoneTextController = TextEditingController();
  final _carNoTextController = TextEditingController();
  String _address = "";
  String _lat = "";
  String _lng = "";
  String _stationName = "";
  String _stationId = "";
  String _aliasName = "";
  int _aliasId = 0;
  @override
  void initState() {
    super.initState();
    _lat =  widget.lat;
    _lng =  widget.lng;
    _stationName =  widget.stationName;
    _stationId =  widget.stationId;
    _aliasName =  widget.aliasName;
    _aliasId =  widget.aliasId;
    _nameTextController.text = widget.username;
    _phoneTextController.text = widget.phone;
    _carNoTextController.text = widget.carPlate;
    _address = widget.address;
    _eventFn = eventBus.on<ClickAddressEvent>().listen((event) {
        setState(() {
          _lat = event.lat !="" ? event.lat : widget.lat ;
          _lng = event.lng !="" ? event.lng : widget.lng ;
          _stationName =event.stationName !="" ? event.stationName : widget.stationName ;
          _stationId = event.stationId !="" ? event.stationId : widget.stationId ;
          String stationName = event.aliasName!=""?"(" + event.stationName + ")":event.stationName;
          _address = event.aliasName !="" || event.stationName != ""? event.aliasName +  stationName: widget.address;
          _aliasName = event.aliasName !=""? event.aliasName : widget.aliasName;
          _aliasId = event.aliasId !=0?event.aliasId : widget.aliasId;
        });
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _eventFn.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          Alib.hideKeyboard(context);
        },
        child:Material(
          color: UIColor.color_main,
          child: Column(
              children: [
                _renderTitle(),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.rpx,vertical: 12.rpx),
                  decoration: const BoxDecoration(
                   color: UIColor.color_content,
                  ),
                  child: Column(
                    children: [
                        Container(
                            height: 0.5.rpx,
                            color: UIColor.color_divider),
                        _renderName(),
                        Container(
                            height: 0.5.rpx,
                            color: UIColor.color_divider),
                        _renderPhone(),
                        Container(
                            height: 0.5.rpx,
                            color: UIColor.color_divider),
                        _renderAddress(),
                        Container(
                            height: 0.5.rpx,
                            color: UIColor.color_divider),
                        _renderCar(),
                    ]
                  )
                ),
                32.hspace,
                Padding(
                  padding: EdgeInsets.all(12.rpx),
                  child: UText.getBkButton(
                    "保存并使用",
                    16.rpx,
                    bkColor: UIColor.color_primary,
                    radius: 12.rpx,
                    width: double.infinity,
                    height: 48.rpx,
                    onPressed: _onClickSubmit,
                  ),
                ),
          ])
        )
    );
  }

  Widget _renderTitle() {
    return Container(
      color: UIColor.color_content,
      width: double.infinity,
      height: MediaQuery.of(context).padding.top + 44.rpx,
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      child:Stack(
        children: [
          SizedBox(width: 50.rpx, child: IconButton(
            iconSize: 18.rpx,
            icon: const Icon(
              Icons.arrow_back_ios_new,
              color: UIColor.color_t1,
            ),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),),
          Center(
              child: UText.get(widget.type == 1?"发货信息":"收货信息", Colors.black, 16.rpx, fw: FontWeight.w600).center
          ),
        ],
      ),
    );
  }

  Widget _renderName() {
    String _name = widget.type == 1?"发货人":"收货人";
    String _placeholder = widget.type == 1?"请输入发货人":"请输入收货人";
    return SizedBox(
      height: 48.rpx,
      child:Row(
          children: [
            SizedBox(
                width: 80.rpx,
                child: UText.get(_name, UIColor.color_t5, 16.rpx)
            ),
            Expanded(
              child: TextField(
                  style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
                  controller: _nameTextController,
                  keyboardType: TextInputType.multiline,
                  maxLines: null,
                  decoration:  InputDecoration(
                    hintText: _placeholder,
                    border:InputBorder.none,
                    hintStyle: const TextStyle(fontSize: 17),
                  )
              ),
            ),
          ]
      ),
    );
  }

  Widget _renderPhone() {
    String _name = widget.type == 1?"发货电话":"收货电话";
    String _placeholder = widget.type == 1?"请输入发货电话":"请输入收货电话";
    return SizedBox(
      height: 48.rpx,
      child:Row(
          children: [
            SizedBox(
                width: 80.rpx,
                child: UText.get(_name, UIColor.color_t5, 16.rpx)
            ),
            Expanded(
              child: TextField(
                  style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
                  controller: _phoneTextController,
                  keyboardType: TextInputType.multiline,
                  maxLines: null,
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp("[0-9]")),
                  ],
                  maxLength: 11,
                  decoration: InputDecoration(
                    counterText: "",
                    hintText: _placeholder,
                    border:InputBorder.none,
                    hintStyle: const TextStyle(fontSize: 17),
                  )
              ),
            ),
          ]
      ),
    );
  }

  Widget _renderAddress() {
    String _name = widget.type == 1?"发货地址":"收货地址";
    String _placeholder = widget.type == 1?"请选择发货地址":"请选择收货地址";
    return SizedBox(
      height: 48.rpx,
      child:Row(
        children: [
          SizedBox(
              width: 80.rpx,
              child: UText.get(_name, UIColor.color_t5, 16.rpx)
          ),
          Expanded(
              child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    if(widget.type == 2) {
                      OpenUtils.open(context,   AddressPage(1,"",0));
                    }
                  },
                  child: Row(
                      children: [
                        LimitedBox(
                          maxWidth: 240.rpx,
                          child:
                          Text(_address == ""?_placeholder:_address, style: TextStyle(color:_address == ""?UIColor.color_t5:UIColor.color_t1,fontSize: 16.rpx,),overflow: TextOverflow.ellipsis,maxLines: 2),
                        ),
                        const Spacer(),
                        widget.type == 1?0.wspace:Icon(Icons.navigate_next, size: 20.rpx, color: UIColor.color_t3),
                      ]
                  )
              )
          ),
        ],
      ),
    );
  }

  Widget _renderCar() {
    return SizedBox(
      height: 48.rpx,
      child:Row(
          children: [
            SizedBox(
                width: 80.rpx,
                child: UText.get("场外车牌", UIColor.color_t5, 16.rpx)
            ),
            Expanded(
              child: TextField(
                  style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
                  controller: _carNoTextController,
                  keyboardType: TextInputType.multiline,
                  maxLines: null,
                  decoration: InputDecoration(
                    hintText: widget.type == 1?"":"例：川A66666",
                    border:InputBorder.none,
                    hintStyle: const TextStyle(fontSize: 17),
                  )
              ),
            ),
          ]
      ),
    );
  }
  _onClickSubmit() {
    String _txt = widget.type == 1?"发":"收";
    if (_nameTextController.text == "") {
      Tip.show("请输入$_txt货人");
      return ;
    }
    if (_phoneTextController.text == "") {
      Tip.show("请输入$_txt货电话");
      return ;
    }
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    if (!exp.hasMatch(_phoneTextController.text)) {
      Tip.show("请输入正确格式的$_txt货电话");
      return ;
    }
    if (_address == "") {
      Tip.show("请选择$_txt货地址");
      return ;
    }
    // if (_carNoTextController.text == "") {
    //   Tip.show("请输入场外车牌");
    //   return ;
    // }
    eventBus.fire(ClickUserInfoEvent(
      _lat,
      _lng,
      _aliasName,
      _aliasId,
      _stationName,
      _stationId,
      _carNoTextController.text,
      _nameTextController.text,
      _phoneTextController.text,
    ));
    Navigator.of(context).pop();
  }
}